//
//  NetworkEngine+imageCloudManager.m
//  MTime
//
//  Created by mtime_lee on 2017/8/15.
//  Copyright © 2017年 imac. All rights reserved.
//

#import "NetworkEngine+imageCloudManager.h"
#import "ImageUploadModel.h"
#define QCloud_AppId @"1252014125"
#define QCloud_Region @"gz"

@implementation NetworkEngine (imageCloudManager)
#pragma mark - 批量图片上传
- (void)getImageURLWithBatchImage:(UIImage *)image batchIndex:(NSUInteger)index completion:(ImageUploadBlock)completion {
    NSDictionary *param = @{@"terminal" :@"ios",
                            @"oneceFlg" :@"true"};
    [self requestWithPath:kURLPath_GetImageStorageSign requestParamter:param reponseObjctClass:[ImageUploadModel class] completionBlock:^(BOOL isSuccess, id object, NSError *error) {
        if (isSuccess) {
            ImageUploadModel *uploadModel = (ImageUploadModel *)object;
            NSData *imageData = UIImagePNGRepresentation([image fixOrientation]);
            NSString *imageType = [Tools contentTypeWithImage:image];
            //设置一个图片的存储路径
            NSString *imagePath = [NSString stringWithFormat:@"%@/Caches/%@_%ld",NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES).firstObject,[Tools getCurrentTimestamp], index];
            // 保存到本地
            [imageData writeToFile:imagePath atomically:YES];
 
            NSString *fileName = [NSString stringWithFormat:@"%@_%@_%ld.%@",kUSER_INFO_MANAGER.userId,[Tools getCurrentTimestamp], index, imageType];
            
            
            NSString *dir = [NSString stringWithFormat:@"/%@",uploadModel.filePath];
            // 上传任务
            COSObjectPutTask *task = [[COSObjectPutTask alloc] initWithPath:imagePath sign:uploadModel.sign bucket:uploadModel.bucket fileName:fileName customAttribute:nil uploadDirectory:dir insertOnly:YES];
            
            // 初始化 业务AppID 服务器地址
            COSClient *client= [[COSClient alloc] initWithAppId:QCloud_AppId withRegion:QCloud_Region];
            
            [client openHTTPSrequset:YES];
            
            client.completionHandler = ^(COSTaskRsp *resp, NSDictionary *context){
                
                //上传返回结果类
                COSObjectUploadTaskRsp *uploadTask = (COSObjectUploadTaskRsp *)resp;
                if (resp.retCode == 0) {
                    //                    NSLog(@"文件上传成功");
                    if (completion) {
                        completion(uploadTask,uploadModel.filePath,fileName,YES,nil);
                    }
                } else {
                    
                    if (completion) {
                        completion(nil,nil,nil,NO,error);
                    }
                }
                
            };
            //上传进度监听
            client.progressHandler = ^(int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite){
                CGFloat process = (CGFloat)totalBytesWritten / totalBytesExpectedToWrite * 100;
                NSLog(@"进度 = %.2f%%", process);
            };
            
            [client putObject:task];
        }else {
            if (completion) {
                completion(nil,nil,nil,NO,error);
            }
        }
    }];
}

#pragma mark - 单图片上传
- (void)getImageURLWithImage:(UIImage *)image completion:(ImageUploadBlock)completion {
    
    NSDictionary *param = @{@"path" :@"/avatar/user",
                                @"oneceFlg" :@"true"};
    //http://zt3-1252014125.coscd.myqcloud.com
    
    [[AccountService loadgetgetSign:@"/avatar/user"]subscribeNext:^(ResponseData* x) {
        if (x.success) {
            NSDictionary *dic = @{@"sign":x.responseRawData[@"data"][@"sign"],@"filePath":param[@"path"]};
            
            NSData *imageData = UIImagePNGRepresentation([image fixOrientation]);
            NSString *imageType = [Tools contentTypeWithImage:image];
            
            //设置一个图片的存储路径
            NSString *imagePath = [NSString stringWithFormat:@"%@/Caches/%@",NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES).firstObject,[Tools getCurrentTimestamp]];
            
            // 保存到本地
            [imageData writeToFile:imagePath atomically:YES];
            //================== kUserInfoManager.userName
            NSString *fileName = [NSString stringWithFormat:@"%@_%@.%@",kUSER_INFO_MANAGER.userId,[Tools getCurrentTimestamp],imageType];
            NSString *dir = [NSString stringWithFormat:@"/%@",dic[@"filePath"]];
            
            
            // 上传任务 (fix:nil)
            COSObjectPutTask *task = [[COSObjectPutTask alloc] initWithPath:imagePath sign:dic[@"sign"] bucket:@"mtime" fileName:fileName customAttribute:nil uploadDirectory:dir insertOnly:YES];
            
            // 初始化 业务AppID 服务器地址
            COSClient *client= [[COSClient alloc] initWithAppId:QCloud_AppId withRegion:QCloud_Region];
            [client openHTTPSrequset:YES];
            
            /* TODO: ================= 上传图片 =================*/
            
            /* TODO: ================= ERROR_CMD_BUCKET_NOTEXIST =================*/
            
            
            client.completionHandler = ^(COSTaskRsp *resp, NSDictionary *context){
                
                //上传返回结果类
                COSObjectUploadTaskRsp *uploadTask = (COSObjectUploadTaskRsp *)resp;
                if (resp.retCode == 0) {
                    //                    NSLog(@"文件上传成功");
                    if (completion) {
                        completion(uploadTask,dic[@"filePath"],fileName,YES,nil);
                    }
                } else {
                    
                    if (completion) {
                        completion(nil,nil,nil,NO,nil);
                    }
                }
            };
            
            //上传进度监听
            client.progressHandler = ^(int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite){
                CGFloat process = (CGFloat)totalBytesWritten / totalBytesExpectedToWrite * 100;
                NSLog(@"进度 = %.2f%%", process);
            };
            
            [client putObject:task];
        }else{
             [Tools showTips:x.errorInfo];
        }
      


        
    }];
    
}


#pragma mark - 多图片上传
-(void)getImagesUpload:(UIImage *)image batchIndex:(NSUInteger)index completion:(ImageUploadBlock)completion{
    NSDictionary *param = @{@"path" :@"/avatar/user",
                            @"oneceFlg" :@"true"};
    //http://zt3-1252014125.coscd.myqcloud.com
    
    [[AccountService loadgetgetSign:@"/avatar/user"]subscribeNext:^(ResponseData* x) {
        if (x.success) {
            NSDictionary *dic = @{@"sign":x.responseRawData[@"data"][@"sign"],@"filePath":param[@"path"]};
            
            NSData *imageData = UIImagePNGRepresentation([image fixOrientation]);
            NSString *imageType = [Tools contentTypeWithImage:image];
            //设置一个图片的存储路径
            NSString *imagePath = [NSString stringWithFormat:@"%@/Caches/%@",NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES).firstObject,[Tools getCurrentTimestamp]];
            
            // 保存到本地
            [imageData writeToFile:imagePath atomically:YES];
            //================== kUserInfoManager.userName
            NSString *fileName = [NSString stringWithFormat:@"%@_%@.%@",kUSER_INFO_MANAGER.userId,[Tools getCurrentTimestamp],imageType];
            NSString *dir = [NSString stringWithFormat:@"/%@",dic[@"filePath"]];
            
            // 上传任务 (fix:nil)
            COSObjectPutTask *task = [[COSObjectPutTask alloc] initWithPath:imagePath sign:dic[@"sign"] bucket:@"mtime" fileName:fileName customAttribute:nil uploadDirectory:dir insertOnly:YES];
            
            // 初始化 业务AppID 服务器地址
            COSClient *client= [[COSClient alloc] initWithAppId:QCloud_AppId withRegion:QCloud_Region];
            [client openHTTPSrequset:YES];
            
            /* TODO: ================= 上传图片 =================*/
            
            /* TODO: ================= ERROR_CMD_BUCKET_NOTEXIST =================*/

            client.completionHandler = ^(COSTaskRsp *resp, NSDictionary *context){
                
                //上传返回结果类
                COSObjectUploadTaskRsp *uploadTask = (COSObjectUploadTaskRsp *)resp;
                if (resp.retCode == 0) {
                    //NSLog(@"文件上传成功");
                    if (completion) {
                        completion(uploadTask,dic[@"filePath"],fileName,YES,nil);
                    }
                } else {
                    
                    if (completion) {
                        completion(nil,nil,nil,NO,nil);
                    }
                }
            };
            
            //上传进度监听
            client.progressHandler = ^(int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite){
                CGFloat process = (CGFloat)totalBytesWritten / totalBytesExpectedToWrite * 100;
                NSLog(@"进度 = %.2f%%", process);
            };
            
            [client putObject:task];
        }else{
             [Tools showTips:x.errorInfo];
        }
        
    }];
}

- (void)syncConcurrent {
    [self beingBackgroundUpdateTask];

    NSLog(@"currentThread---%@",[NSThread currentThread]);  // 打印当前线程
    NSLog(@"syncConcurrent---begin");
    
    dispatch_queue_t queue = dispatch_queue_create("net.bujige.testQueue", DISPATCH_QUEUE_CONCURRENT);
    
    dispatch_sync(queue, ^{
        // 追加任务1
        for (int i = 0; i < 5; ++i) {
            [NSThread sleepForTimeInterval:2];              // 模拟耗时操作
            NSLog(@"1---%@",[NSThread currentThread]);      // 打印当前线程
        }
    });
    
    dispatch_sync(queue, ^{
        // 追加任务2
        for (int i = 0; i < 5; ++i) {
            [NSThread sleepForTimeInterval:2];              // 模拟耗时操作
            NSLog(@"2---%@",[NSThread currentThread]);      // 打印当前线程
        }
    });
    
    dispatch_sync(queue, ^{
        // 追加任务3
        for (int i = 0; i < 5; ++i) {
            [NSThread sleepForTimeInterval:2];              // 模拟耗时操作
            NSLog(@"3---%@",[NSThread currentThread]);      // 打印当前线程
        }
    });
    
    NSLog(@"syncConcurrent---end");
    // 在这里加上你需要长久运行的代码
    [self endBackgroundUpdateTask];

}


- (void)beingBackgroundUpdateTask
{
    self.backgroundUpdateTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
        [self endBackgroundUpdateTask];
    }];
}

- (void)endBackgroundUpdateTask
{
    [[UIApplication sharedApplication] endBackgroundTask: self.backgroundUpdateTask];
    self.backgroundUpdateTask = UIBackgroundTaskInvalid;
}






- (void)getImageURLWithImage:(UIImage *)image Path:(NSString*)Path fileName:(NSString*)fileName1 batchIndex:(NSUInteger)index Timestamp:(NSString*)Timestamp completion:(ImageUploadBlock)completion{
    NSDictionary *param = @{@"path" :Path,
                            @"oneceFlg" :@"true"};
    //http://zt3-1252014125.coscd.myqcloud.com
    
    [[AccountService loadgetgetSign:Path]subscribeNext:^(ResponseData* x) {
        if (x.success) {
            NSDictionary *dic = @{@"sign":x.responseRawData[@"data"][@"sign"],@"filePath":param[@"path"]};
            
            NSData *imageData = UIImagePNGRepresentation([image fixOrientation]);
            //设置一个图片的存储路径
            
            NSString *imagePath = [NSString stringWithFormat:@"%@/Caches/%@_%ld",NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES).firstObject,Timestamp, index];
            
            // 保存到本地
            [imageData writeToFile:imagePath atomically:YES];
            
            //================== kUserInfoManager.userName

            NSString *dir = [NSString stringWithFormat:@"/%@",dic[@"filePath"]];
            
            
            // 上传任务 (fix:nil)
            COSObjectPutTask *task = [[COSObjectPutTask alloc] initWithPath:imagePath sign:dic[@"sign"] bucket:@"mtime" fileName:fileName1 customAttribute:nil uploadDirectory:dir insertOnly:YES];
            
            // 初始化 业务AppID 服务器地址
            COSClient *client= [[COSClient alloc] initWithAppId:QCloud_AppId withRegion:QCloud_Region];
            [client openHTTPSrequset:YES];
            
            /* TODO: ================= 上传图片 =================*/
            
            /* TODO: ================= ERROR_CMD_BUCKET_NOTEXIST =================*/
            
            
            client.completionHandler = ^(COSTaskRsp *resp, NSDictionary *context){
                
                //上传返回结果类
                COSObjectUploadTaskRsp *uploadTask = (COSObjectUploadTaskRsp *)resp;
                if (resp.retCode == 0) {
                    //                    NSLog(@"文件上传成功");
                    if (completion) {
                        completion(uploadTask,dic[@"filePath"],fileName1,YES,nil);
                    }
                } else {
                    
                    if (completion) {
                        completion(nil,nil,nil,NO,nil);
                    }
                }
            };
            
            //上传进度监听
            client.progressHandler = ^(int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite){
                CGFloat process = (CGFloat)totalBytesWritten / totalBytesExpectedToWrite * 100;
                NSLog(@"进度 = %.2f%%", process);
            };
            
            [client putObject:task];
        }else{
            if (completion) {
                completion(nil,nil,nil,NO,nil);
            }
            //             
        }
        
    }];
    
    
    
    
    
    
    
//    NSDictionary *param = @{@"path" :Path,
//                            @"oneceFlg" :@"true"};
//    //http://zt3-1252014125.coscd.myqcloud.com
//
//    [[AccountService loadgetgetSign:Path]subscribeNext:^(ResponseData* x) {
//        if (x.success) {
//            NSDictionary *dic = @{@"sign":x.responseRawData[@"data"][@"sign"],@"filePath":param[@"path"]};
//
//            NSData *imageData = UIImagePNGRepresentation([image fixOrientation]);
//            NSString *imageType = [Tools contentTypeWithImage:image];
//            //设置一个图片的存储路径
//
//            NSString *imagePath = [NSString stringWithFormat:@"%@/Caches/%@_%ld",NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES).firstObject,[Tools getCurrentTimestamp], index];
//
//            // 保存到本地
//            [imageData writeToFile:imagePath atomically:YES];
//
//            //================== kUserInfoManager.userName
//            NSString *fileName = fileName1;
//            //[NSString stringWithFormat:@"%@_%@_%ld.%@",kUSER_INFO_MANAGER.userId,[Tools getCurrentTimestamp],index,imageType];
//
//            NSString *dir = [NSString stringWithFormat:@"/%@",dic[@"filePath"]];
//
//            // 上传任务 (fix:nil)
//            COSObjectPutTask *task = [[COSObjectPutTask alloc] initWithPath:imagePath sign:dic[@"sign"] bucket:@"mtime" fileName:fileName customAttribute:nil uploadDirectory:dir insertOnly:YES];
//
//            // 初始化 业务AppID 服务器地址
//            COSClient *client= [[COSClient alloc] initWithAppId:QCloud_AppId withRegion:QCloud_Region];
//            [client openHTTPSrequset:YES];
//
//            /* TODO: ================= 上传图片 =================*/
//
//            /* TODO: ================= ERROR_CMD_BUCKET_NOTEXIST =================*/
//
//            client.completionHandler = ^(COSTaskRsp *resp, NSDictionary *context){
//
//                //上传返回结果类
//                COSObjectUploadTaskRsp *uploadTask = (COSObjectUploadTaskRsp *)resp;
//                if (resp.retCode == 0) {
//                    //                    NSLog(@"文件上传成功");
//                    if (completion) {
//                        completion(uploadTask,dic[@"filePath"],fileName,YES,nil);
//                    }
//                } else {
//
//                    if (completion) {
//                        completion(nil,nil,nil,NO,nil);
//                    }
//                }
//            };
//
//            //上传进度监听
//            client.progressHandler = ^(int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite){
//                CGFloat process = (CGFloat)totalBytesWritten / totalBytesExpectedToWrite * 100;
//                NSLog(@"进度 = %.2f%%", process);
//            };
//
//            [client putObject:task];
//        }else{
//            if (completion) {
//                completion(nil,nil,nil,NO,nil);
//            }
////             
//        }
//
//    }];
}

/** 原来多图上传 */
- (void)getImageURLWithImageOld:(UIImage *)image Path:(NSString*)Path batchIndex:(NSUInteger)index completion:(ImageUploadBlock)completion{
    NSDictionary *param = @{@"path" :Path,
                            @"oneceFlg" :@"true"};
    //http://zt3-1252014125.coscd.myqcloud.com
    
    [[AccountService loadgetgetSign:Path]subscribeNext:^(ResponseData* x) {
        if (x.success) {
            NSDictionary *dic = @{@"sign":x.responseRawData[@"data"][@"sign"],@"filePath":param[@"path"]};
            
            NSData *imageData = UIImagePNGRepresentation([image fixOrientation]);
            NSString *imageType = [Tools contentTypeWithImage:image];
            //设置一个图片的存储路径
            
            NSString *imagePath = [NSString stringWithFormat:@"%@/Caches/%@_%ld",NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES).firstObject,[Tools getCurrentTimestamp], index];
            
            // 保存到本地
            [imageData writeToFile:imagePath atomically:YES];
            
            //================== kUserInfoManager.userName
            NSString *fileName = [NSString stringWithFormat:@"%@_%@_%ld.%@",kUSER_INFO_MANAGER.userId,[Tools getCurrentTimestamp],index,imageType];
            
            NSString *dir = [NSString stringWithFormat:@"/%@",dic[@"filePath"]];
            
            
            // 上传任务 (fix:nil)
            COSObjectPutTask *task = [[COSObjectPutTask alloc] initWithPath:imagePath sign:dic[@"sign"] bucket:@"mtime" fileName:fileName customAttribute:nil uploadDirectory:dir insertOnly:YES];
            
            // 初始化 业务AppID 服务器地址
            COSClient *client= [[COSClient alloc] initWithAppId:QCloud_AppId withRegion:QCloud_Region];
            [client openHTTPSrequset:YES];
            
            /* TODO: ================= 上传图片 =================*/
            
            /* TODO: ================= ERROR_CMD_BUCKET_NOTEXIST =================*/
            
            
            client.completionHandler = ^(COSTaskRsp *resp, NSDictionary *context){
                
                //上传返回结果类
                COSObjectUploadTaskRsp *uploadTask = (COSObjectUploadTaskRsp *)resp;
                if (resp.retCode == 0) {
                    //                    NSLog(@"文件上传成功");
                    if (completion) {
                        completion(uploadTask,dic[@"filePath"],fileName,YES,nil);
                    }
                } else {
                    
                    if (completion) {
                        completion(nil,nil,nil,NO,nil);
                    }
                }
            };
            
            //上传进度监听
            client.progressHandler = ^(int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite){
                CGFloat process = (CGFloat)totalBytesWritten / totalBytesExpectedToWrite * 100;
                NSLog(@"进度 = %.2f%%", process);
            };
            
            [client putObject:task];
        }else{
            if (completion) {
                completion(nil,nil,nil,NO,nil);
            }
            //             
        }
        
    }];
}


@end









//[self requestWithPath:kURLPath_GetImageStorageSign requestParamter:param reponseObjctClass:[ImageUploadModel class] completionBlock:^(BOOL isSuccess, id object, NSError *error) {
//    if (isSuccess) {
//        ImageUploadModel *uploadModel = (ImageUploadModel *)object;
//        NSData *imageData = UIImagePNGRepresentation([image fixOrientation]);
//        NSString *imageType = [Tools contentTypeWithImage:image];
//        //设置一个图片的存储路径
//        NSString *imagePath = [NSString stringWithFormat:@"%@/Caches/%@_%ld",NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES).firstObject,[Tools getCurrentTimestamp], index];
//
//        // 保存到本地
//        [imageData writeToFile:imagePath atomically:YES];
//
//        NSString *fileName = [NSString stringWithFormat:@"%@_%@_%ld.%@",kUSER_INFO_MANAGER.userId,[Tools getCurrentTimestamp], index, imageType];
//
//
//        NSString *dir = [NSString stringWithFormat:@"/%@",uploadModel.filePath];
//        // 上传任务
//        COSObjectPutTask *task = [[COSObjectPutTask alloc] initWithPath:imagePath sign:uploadModel.sign bucket:uploadModel.bucket fileName:fileName customAttribute:nil uploadDirectory:dir insertOnly:YES];
//
//        // 初始化 业务AppID 服务器地址
//        COSClient *client= [[COSClient alloc] initWithAppId:QCloud_AppId withRegion:QCloud_Region];
//
//        [client openHTTPSrequset:YES];
//
//        client.completionHandler = ^(COSTaskRsp *resp, NSDictionary *context){
//
//            //上传返回结果类
//            COSObjectUploadTaskRsp *uploadTask = (COSObjectUploadTaskRsp *)resp;
//            if (resp.retCode == 0) {
//                //                    NSLog(@"文件上传成功");
//                if (completion) {
//                    completion(uploadTask,uploadModel.filePath,fileName,YES,nil);
//                }
//            } else {
//
//                if (completion) {
//                    completion(nil,nil,nil,NO,error);
//                }
//            }
//
//        };
//        //上传进度监听
//        client.progressHandler = ^(int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite){
//            CGFloat process = (CGFloat)totalBytesWritten / totalBytesExpectedToWrite * 100;
//            NSLog(@"进度 = %.2f%%", process);
//        };
//
//        [client putObject:task];
//    }else {
//        if (completion) {
//            completion(nil,nil,nil,NO,error);
//        }
//    }
//    }];
